<?php

namespace app\common\library;

use app\common\exception\UploadException;
use app\common\model\Attachment;
use OSS\OssClient;
use OSS\Core\OssException;

class UploadAliyun extends Upload
{

    /**
     * 上传图片到阿里云
     * @return \app\common\model\attachment|\think\Model
     * @throws UploadException
     */
    public function upload($savekey = null)
    {
        if (empty($this->file)) {
            throw new UploadException(__('No file upload or server upload limit exceeded'));
        }

        $this->checkSize();
        $this->checkExecutable();
        $this->checkMimetype();
        $this->checkImage();

        $savekey = $savekey ? $savekey : $this->getSavekey();
        $savekey = ltrim($savekey, '/');

        $sourceFile = $this->file->getRealPath() ?: $this->file->getPathname();
        $upload = [];
        try {
            $ossClient = new OssClient(config("aliyun_oss.access_id"), config("aliyun_oss.access_secret"), config("aliyun_oss.endpoint"));
            $res = $ossClient->uploadFile(config("aliyun_oss.bucket"), $savekey, $sourceFile);
            if ($res == null) {
                throw new UploadException(__('No file upload or server upload limit exceeded'));
            }

            $upload["url"] = $res["info"]["url"];
            $upload["etag"] = $res["etag"];
            $upload["oss-request-url"] = $res["oss-request-url"];
            $upload["request-id"] = $res["x-oss-request-id"];
            $upload["Content-Type"] = $res["oss-requestheaders"]["Content-Type"];
        } catch (OssException $e) {
            throw new UploadException($e->getMessage());
        }

        if (count($upload) == 0) {
            throw new UploadException(__('No file upload or server upload limit exceeded'));
        }

        $cdns = config("aliyun_oss.cndurl");

        $params = array(
            'admin_id' => (int)session('admin.id'),
            'user_id' => (int)cookie('uid'),
            'filename' => substr(htmlspecialchars(strip_tags($this->fileInfo['name'])), 0, 100),
            'filesize' => $this->fileInfo['size'],
            'imagewidth' => $this->fileInfo['imagewidth'],
            'imageheight' => $this->fileInfo['imageheight'],
            'imagetype' => $upload["Content-Type"],
            'imageframes' => 0,
            'mimetype' => $this->fileInfo['type'],
            'url' => $cdns . $savekey,
            'uploadtime' => time(),
            'storage' => 'aliyun',
            'sha1' => $upload["etag"],
            'extparam' => $upload["request-id"],
        );
        $attachment = new Attachment();
        $attachment->data(array_filter($params));
        $attachment->save();

        \think\Hook::listen("upload_after", $attachment);
        return $attachment;
    }
}

